/**
 * 
 */
package com.wiretap.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;

import com.wiretap.cache.AdminCache;
import com.wiretap.dao.AdminDao;
import com.wiretap.po.Administrator;

/**
 * @author zzy
 * @category 管理员操作DAO实现类
 */
public class AdminDaoImpl implements AdminDao {
	private SessionFactory sessionFactory;

	/**
	 * 增加管理员
	 */
	@Override
	public void addAdministrator(Administrator administrator) throws Exception {
		try {
			this.sessionFactory.getCurrentSession().persist(administrator);
			AdminCache.clearCache();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("增加管理员时发生异常");
		}
	}

	/**
	 * 获取管理员信息
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Administrator getAdministratorByName(final String username) throws Exception {
		try {
			List<Administrator> administrators = sessionFactory.getCurrentSession().createQuery("from Administrator a where a.username=:username").setString("username", username).list();
			if (administrators.size() > 0) {
				return administrators.get(0);
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("获取管理员信息发生异常");
		}
	}

	/**
	 * 更新管理员信息
	 */
	@Override
	public void updateAdministrator(Administrator administrator) throws Exception {
		try {
			sessionFactory.getCurrentSession().update(administrator);
			AdminCache.clearCache();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("更新管理员信息发生异常");
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Administrator> getAdministrators() throws Exception {
		try {
			List<Administrator> admins = AdminCache.getAdmins();
			if (!admins.isEmpty()) {
				return admins;
			} else {
				List<Administrator> result = sessionFactory.getCurrentSession().createQuery("from Administrator a where a.superAdmin=:superAdmin").setBoolean("superAdmin", false).list();
				AdminCache.setCache(result);
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("获取管理员列表发生异常");
		}
	}

	@Override
	public void removeAdmin(String id) throws Exception {
		try {
			sessionFactory.getCurrentSession().createQuery("delete from Administrator a where a.id=:id").setString("id", id).executeUpdate();
			AdminCache.clearCache();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("删除用户时发生异常");
		}
	}

	/**
	 * @param sessionFactory
	 *            the sessionFactory to set
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}
